/*
 * @Descripttion: 
 * @Author: voanit
 * @Date: 2022-06-01 17:49:03
 * @LastEditors: voanit
 * @LastEditTime: 2022-06-08 12:27:18
 */
import { useState, useEffect, useRef } from 'react'
export const useCountDown = (callback: () => void) => {
  const [count, setCount] = useState(0)
  let timeId = useRef<{ id: number }>({ id: 0 })
  useEffect(() => {
    return () => {
      // 销毁
      // eslint-disable-next-line react-hooks/exhaustive-deps
      clearInterval(timeId.current.id)
    }
  }, [])
  useEffect(() => {
    // console.log(1111222);
    if (count <= 1) {
      // 清除定时器
      clearInterval(timeId.current.id)
      callback && callback()
    }

  }, [callback, count])
  const start = (n: number) => {
    setCount(n)
    timeId.current.id = window.setInterval(() => {
      // count--
      setCount(count => count - 1)
    }, 1000)
  }

  return { start, count }
}